package com.ls.lserp.modules.material.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.modules.order.entity.SpecimenProduction;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.OgnizationEntity;
import com.ls.lserp.modules.material.entity.SlopworkInRequest;
import com.ls.lserp.modules.material.service.SlopworkInRequestService;
import com.ls.lserp.modules.sys.utils.SequenceUtil;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/slopwork/inrequest/")
public class SlopworkInRequestController extends BaseController {

    // 保存 编辑 删除 方法
    @Autowired
    private SlopworkInRequestService slopworkInRequestService;
    @Autowired
    Configuration freemarkerConfiguration;

    @ModelAttribute
    public SlopworkInRequest get(@RequestParam(required = false) String id) {

        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {
            // 执行查询语句 查询基本信息

            return slopworkInRequestService.get (Long.parseLong (id));
        } else {
            // 若为空，实例化
            return new SlopworkInRequest ();
        }
    }

    /**
     * @return url
     * @Title: 画面跳转用
     */
    @RequiresPermissions("slopwork:inrequest:view")
    @RequestMapping(value = {""})
    public String list(Model model) {
        // 画面跳转
        return "modules/material/slopworkInRequest";
    }

    /**
     * @param slopworkInRequest
     * @param request
     * @param response
     * @param model
     * @return searchList
     * @throws Exception
     * @Title: 画面检索
     * @Description: 查询页面
     */
    @RequiresPermissions("slopwork:inrequest:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(SlopworkInRequest slopworkInRequest, HttpServletRequest request, HttpServletResponse response,
                             Model model) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute (Global.LIST_NAME, "slopworkInRequest");
        // 拼接字符串供分页使用
        StringBuilder searchParam = new StringBuilder ();
        // 入库单号
        searchParam.append ("&inventoryRequestNo=");
        searchParam.append (slopworkInRequest.getInventoryRequestNo ());
        // 合同订单号
        searchParam.append ("&customerContractNo=");
        searchParam.append (slopworkInRequest.getCustomerContractNo ());
        // 客户名称
        searchParam.append ("&customerName=");
        searchParam.append (slopworkInRequest.getCustomerName ());
        // 日期
        searchParam.append ("&dateFrom=");
        searchParam.append (slopworkInRequest.getDateFrom ());
        searchParam.append ("&dateTo=");
        searchParam.append (slopworkInRequest.getDateTo ());
        // 状态
        searchParam.append ("&tabPageStatus=");
        searchParam.append (slopworkInRequest.getTabPageStatus ());
        // 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam.toString ());

        // 查询一览页面数据
        Page <SlopworkInRequest> page = slopworkInRequestService.findList (new Page <SlopworkInRequest> (request, response), slopworkInRequest);
        // 读取系统路径
        String strUri = request.getContextPath () + Global.getAdminPath ();
        // 读取文件生成字符串
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("slopworkInRequests", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("slopworkInRequest.ftl"), map);
        listMap.put ("slopworkInRequest", strHtml);
        listMap.put ("page", page.getHtml ());

        // ajax返回结果
        return renderString (response, listMap);
    }

    /**
     * @param @param  inventoryRequest
     * @param @param  model
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: delRequestDetail
     * @Description: 删除入库申请明细
     */

    @RequiresPermissions("slopwork:inrequest:edit")
    @RequestMapping(value = "delAllDetails")
    public String delAllDetails(SlopworkInRequest slopworkInRequest, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {

            slopworkInRequest.setRequestDetailsList (new ArrayList <SlopworkInRequest> ());

            // 将page值赋值给mvc model层返回jsp页面
            model.addAttribute ("slopworkInRequest", slopworkInRequest);

            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        }
    }

    /**
     * 进入编辑页面
     *
     * @param slopworkInRequest
     * @param model
     * @return
     */
    @RequiresPermissions("slopwork:inrequest:edit")
    @RequestMapping(value = "form")
    public String form(SlopworkInRequest slopworkInRequest, RedirectAttributes redirectAttributes, Model model, HttpSession session) {
        //getStatusFlg的值就是从样品入库传过来的id值
        //编辑的时候传过来的入库明细表i_clothes_request_p的主键
        //创建的时候传过来的id是s_sample_size_quantity_s.的主键
         if(slopworkInRequest.getStatusFlg() != null)
         {
             Long id = slopworkInRequest.getStatusFlg();
             /*先判断该样品是否已经申请入库*/
             List<SlopworkInRequest> list =  slopworkInRequestService.getSamplyData(id);
             if(list!=null && list.size() >0){
                 //编辑
                 slopworkInRequest.setInventoryRequestNo(list.get(0).getInventoryRequestNo());
             }else{
                 //创建
                 list =  slopworkInRequestService.getSamplyDataCreate(id);
                 slopworkInRequest.setRequestDetailsList(list);
                 if(!CollectionsUtils.isEmpty(list) && list.size() > 0){
                     //样品需求单ID 样品的每条size申请一次入库list里面只有一条数据
                      slopworkInRequest.setSampleRequestId(list.get(0).getSampleRequestId());
                     //获取getStyleNo
                     String sequenceNo = SequenceUtil.getStyleRequest("IN",slopworkInRequest.getRequestDetailsList().get(0).getStyleNo (),4).getReturnCode();
                     slopworkInRequest.setInventoryRequestNo (sequenceNo);
                 }

             }
             slopworkInRequest.setRequestDetailsList(list);
             slopworkInRequest.setInventoryCategory(ResourcesUtil.getConfig ("clothes_in_category_Samply"));
             slopworkInRequest.setStatusFlg(id);
             slopworkInRequest.setStyleId(slopworkInRequest.getRequestDetailsList().get(0).getStyleId());
         }else{
        // 生产制单
        List <SlopworkInRequest> resultProductionList = slopworkInRequestService.getProductionList ();
        slopworkInRequest.setProductionNoList (resultProductionList);

        // 加工厂
        List <OgnizationEntity> resultFabricatList = slopworkInRequestService.getFabricatList ();
        slopworkInRequest.setFabricatList (resultFabricatList);

        // 创建
        if (slopworkInRequest.getId () == null) {
            // 入库单条码
            slopworkInRequest.setStockBarCode (SequenceUtil.slopworkRequestbarcode ().getReturnCode ());
            // 编辑
        } else {
            // 入库申请类别,生产制单
            if (slopworkInRequest.getInventoryCategory ().equals (ResourcesUtil.getConfig ("clothes_in_category_production"))) {
                // 下拉款式
                List <SlopworkInRequest> styleList = new ArrayList <SlopworkInRequest> ();
                SlopworkInRequest sl = new SlopworkInRequest ();
                sl.setStyleId (slopworkInRequest.getStyleId ());
                sl.setCustomerStyleNo (slopworkInRequest.getCustomerStyleNo ());
                styleList.add (sl);
                slopworkInRequest.setStyleList (styleList);
                // 入库申请类别,外发生产
            } else if (slopworkInRequest.getInventoryCategory ().equals (ResourcesUtil.getConfig ("clothes_in_category_processing"))) {
                // 下拉外发合同
                SlopworkInRequest pSlopworkInRequest = new SlopworkInRequest ();
                pSlopworkInRequest.setFabricatId (slopworkInRequest.getFabricatId ());
                List <SlopworkInRequest> processList = slopworkInRequestService.getContractProcessingList (pSlopworkInRequest);
                slopworkInRequest.setContractProcessList (processList);

                // 下拉款式
                pSlopworkInRequest = new SlopworkInRequest ();
                pSlopworkInRequest.setContractProcessId (slopworkInRequest.getContractProcessId ());
                List <SlopworkInRequest> styleList = slopworkInRequestService.getStyleList (pSlopworkInRequest);
                slopworkInRequest.setStyleList (styleList);
            }

            // 查找入库申请明细
            List <SlopworkInRequest> resultRequestList = slopworkInRequestService.findShowRequestDetailList (slopworkInRequest);
            slopworkInRequest.setRequestDetailsList (resultRequestList);
        }
         }
        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("slopworkInRequest", slopworkInRequest);

        // 返回页面地址
        return "modules/material/slopworkInRequestCreate";
    }

    /**
     * @param @param  productionId
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: findStyle
     * @Description: 生产制单联动
     */

    @RequiresPermissions("slopwork:inrequest:edit")
    @RequestMapping(value = "selProduction")
    public String selProduction(Long productionId, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            SlopworkInRequest pSlopworkInRequest = new SlopworkInRequest ();
            pSlopworkInRequest.setProductionId (productionId);
            SlopworkInRequest slopworkInfo = slopworkInRequestService.getProduction (pSlopworkInRequest);

            if (slopworkInfo != null) {
                String sequenceNo = SequenceUtil.getStyleRequest("IN",slopworkInfo.getStyleNo (),4).getReturnCode();
                slopworkInfo.setInventoryRequestNo (sequenceNo);
                List <SlopworkInRequest> styleList = new ArrayList <SlopworkInRequest> ();
                SlopworkInRequest sl = new SlopworkInRequest ();
                sl.setStyleId (slopworkInfo.getStyleId ());
                sl.setCustomerStyleNo (slopworkInfo.getCustomerStyleNo ());
                styleList.add (sl);
                slopworkInfo.setStyleList (styleList);

                pSlopworkInRequest = new SlopworkInRequest ();
                pSlopworkInRequest.setContractId (slopworkInfo.getContractId ());
                pSlopworkInRequest.setIndentId (slopworkInfo.getIndentId ());
                pSlopworkInRequest.setStyleId (slopworkInfo.getStyleId ());
                slopworkInfo.setRequestDetailsList (slopworkInRequestService.findCreateRequestDetailList (pSlopworkInRequest));
            }
            // 将page值赋值给mvc model层返回jsp页面
            model.addAttribute ("slopworkInRequest", slopworkInfo);

            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        }
    }

    /**
     * @param @param  productionId
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: findStyle
     * @Description: 生产制单联动
     */

    @RequiresPermissions("slopwork:inrequest:edit")
    @RequestMapping(value = "selFabricat")
    public String selFabricat(Long fabricatId, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            SlopworkInRequest pSlopworkInRequest = new SlopworkInRequest ();
            pSlopworkInRequest.setFabricatId (fabricatId);
            List <SlopworkInRequest> slopworkList = slopworkInRequestService.getContractProcessingList (pSlopworkInRequest);

            SlopworkInRequest resultSlop = new SlopworkInRequest ();
            resultSlop.setContractProcessList (slopworkList);

            // 将page值赋值给mvc model层返回jsp页面
            model.addAttribute ("slopworkInRequest", resultSlop);

            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        }
    }

    /**
     * @param @param  productionId
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: findStyle
     * @Description: 样品需求联动
     */

    @RequiresPermissions("slopwork:inrequest:edit")
    @RequestMapping(value = "selContractProcess")
    public String selContractProcess(Long contractProcessId, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            SlopworkInRequest pSlopworkInRequest = new SlopworkInRequest ();
            pSlopworkInRequest.setContractProcessId (contractProcessId);
            List <SlopworkInRequest> slopworkList = slopworkInRequestService.getStyleList (pSlopworkInRequest);

            SlopworkInRequest resultSlop = new SlopworkInRequest ();
            resultSlop.setStyleList (slopworkList);

            // 将page值赋值给mvc model层返回jsp页面
            model.addAttribute ("slopworkInRequest", resultSlop);

            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        }
    }

    /**
     * @param @param  productionId
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: selStyle
     * @Description: 选择款
     */

    @RequiresPermissions("slopwork:inrequest:edit")
    @RequestMapping(value = "selStyle")
    public String selStyle(Long contractProcessId, Long styleId, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            SlopworkInRequest pSlopworkInRequest = new SlopworkInRequest ();
            pSlopworkInRequest.setContractProcessId (contractProcessId);
            pSlopworkInRequest.setStyleId (styleId);
            SlopworkInRequest slopworkInfo = slopworkInRequestService.getContractNo (pSlopworkInRequest);
            // 设置入库单号"IN"+款号
            if (slopworkInfo != null) {
                String sequenceNo = SequenceUtil.getStyleRequest("IN",slopworkInfo.getStyleNo (),4).getReturnCode();
                slopworkInfo.setInventoryRequestNo (sequenceNo);
                pSlopworkInRequest = new SlopworkInRequest ();
                pSlopworkInRequest.setContractId (slopworkInfo.getContractId ());
                pSlopworkInRequest.setIndentId (slopworkInfo.getIndentId ());
                pSlopworkInRequest.setStyleId (styleId);
                slopworkInfo.setRequestDetailsList (slopworkInRequestService.findCreateRequestDetailList (pSlopworkInRequest));
            }

            // 将page值赋值给mvc model层返回jsp页面
            model.addAttribute ("slopworkInRequest", slopworkInfo);

            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 返回地址
            return "modules/material/slopworkInRequestCreate";
        }
    }

    /**
     * 保存信息
     *
     * @param slopworkInRequest
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("slopwork:inrequest:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(SlopworkInRequest slopworkInRequest, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (slopworkInRequest.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            SlopworkInRequest inventoryRequestNew = get (slopworkInRequest.getId ().toString ());
            // 判断数据是否删除
            if (inventoryRequestNew == null || BaseEntity.DEL_FLAG_DELETE.equals (inventoryRequestNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }

            // 排他处理
            if (slopworkInRequest.getVersion () == get (slopworkInRequest.getId ().toString ()).getVersion ()) {

                // 版本号加1
                slopworkInRequest.setVersion (slopworkInRequest.getVersion () + 1);
            } else {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }

            // 入库申请类别,生产制单
            if (slopworkInRequest.getInventoryCategory ().equals (ResourcesUtil.getConfig ("clothes_in_category_production"))) {
                // 清空外发合同订单id
                slopworkInRequest.setContractProcessId (null);
                // 入库申请类别,外发生产
            } else if (slopworkInRequest.getInventoryCategory ().equals (ResourcesUtil.getConfig ("clothes_in_category_processing"))) {
                // 清空生产制单id
                slopworkInRequest.setProductionId (null);
            }
        }

        // 保存入库申请
        slopworkInRequestService.saveInventoryRequest (slopworkInRequest);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("inventory_request_save_success")));
    }

    /**
     * 进入查看页面
     *
     * @param slopworkInRequest
     * @param model
     * @return
     */
    @RequiresPermissions("slopwork:inrequest:view")
    @RequestMapping(value = "show")
    public String show(SlopworkInRequest slopworkInRequest, Model model) {
        // 查找入库申请明细
        List <SlopworkInRequest> resultRequestList = new ArrayList<SlopworkInRequest>();
        if(ResourcesUtil.getConfig ("clothes_in_category_Samply").equals(slopworkInRequest.getInventoryCategory())){
            //样品入库明细
           resultRequestList = slopworkInRequestService.findSamplyShowRequestDetailList(slopworkInRequest);
        }else{
            resultRequestList = slopworkInRequestService.findShowRequestDetailList (slopworkInRequest);
        }
        slopworkInRequest.setRequestDetailsList (resultRequestList);
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("slopworkInRequest", slopworkInRequest);
        // 返回页面地址
        return "modules/material/slopworkInRequestShow";
    }
}
